import { defineStore } from 'pinia'
import type { TabItem } from '@/types/store'
import { routeMap } from '@/router'

const id = 'tab'
const initTabActive = 'home'

const store = defineStore(id, {
  state: () => ({
    tabs: [
      {
        title: '控制台',
        icon: 'House',
        name: initTabActive,
        // 'menu'-来源于菜单，'button'-来源页面按钮
        source: 'menu',
        // 当 source = button 的时候，所属菜单项的 name
        // 当 source = menu 的时候，保留空字符串或者undefined即可
        menu: '',
        closable: false,
        kaName: 'HomeView'
      }
    ] as TabItem[],
    tabActive: initTabActive
  }),
  getters: {
    // 获取 TabActive 对应的 tab
    tab(state) {
      return state.tabs.find((tab) => tab.name === state.tabActive)
    }
  },
  actions: {
    push(tab: Omit<TabItem, 'kaName'>) {
      const index = this.tabs.findIndex((t) => t.name === tab.name)
      if (index > -1) {
        // update
        Object.assign(this.tabs[index], tab)
        return
      }
      if (!routeMap[tab.name]) {
        return
      }
      this.tabs.push(
        Object.assign(
          {
            closable: true,
            kaName: routeMap[tab.name].kaName
          },
          tab
        )
      )
    },
    close(name: string) {
      const index = this.tabs.findIndex((tab) => tab.name === name)
      if (index === -1) {
        return
      }

      if (this.tabActive === name) {
        const { menu } = this.tabs[index]
        this.tabActive = menu ? menu : this.tabs[index - 1].name
      }

      // 如果 此时 this.tabActive 恰好是关闭的，需要返回 home
      if (this.tabs.findIndex((tab) => tab.name === this.tabActive) === -1) {
        this.tabActive = initTabActive
      }

      this.tabs.splice(index, 1)
    },
    exchangeByIndex(newIndex: number, oldIndex: number) {
      const tabBak = this.tabs[oldIndex]
      this.tabs.splice(oldIndex, 1)
      this.tabs.splice(newIndex, 0, tabBak)
    }
  },
  persist: {
    key: id
    // 需要持久化存储的 key
    // paths: ['token', 'user', 'menuActive', 'tabs', 'layout', 'collapse']
  }
})

export default store
